package com.cn.service.server.bc.Impl;


import com.cn.bean.pojo.bc.Menu;
import com.cn.mapper.dao.db1.bc.MenuDao;
import com.cn.service.server.bc.MenuServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServerImpl implements MenuServer {
    private final MenuDao menuDao;

    @Autowired(required=false)
    public MenuServerImpl(MenuDao menuDao) {
        this.menuDao = menuDao;
    }

    @Override
    public List<Menu> selectMenuList(String userName) {
        List<Menu> menus = menuDao.selectMenuList(userName);
        List<Menu> menuNodes = buildMenuTree(menus);

        return menuNodes;
    }

    private List<Menu> buildMenuTree(List<Menu> menus) {
        Map<Integer, Menu> menuMap = new HashMap<>();
        List<Menu> menuTree = new ArrayList<>();

        for (Menu menu : menus) {
            menuMap.put(menu.getMenuId(), menu);
        }

        for (Menu menu : menus) {
            if (menu.getParentId() == 0) {
                menuTree.add(menu);
            } else {
                Menu parentNode = menuMap.get(menu.getParentId());
                if (parentNode != null) {
                    if (parentNode.getChildren() == null) {
                        parentNode.setChildren(new ArrayList<>());
                    }
                    parentNode.getChildren().add(menu);
                }
            }
        }

        return menuTree;
    }

}
